package com.zhang.family_doctor.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.UndeclaredThrowableException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 对服务器端出现500异常进行统一处理
     */
    @ExceptionHandler(value = ServiceException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorHandler makeExcepton(Throwable e, HttpServletRequest request) {
        String message = e.getMessage();
        if (e instanceof UndeclaredThrowableException){
            Throwable undeclaredThrowable = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            message = undeclaredThrowable.getMessage();
        }
        ErrorHandler errorHandler = ErrorHandler.fail(e.getClass().getName()+ ": " +message);
        log.error("请求的地址：{},出现的异常：{}", request.getRequestURL(), e);
        System.out.println("ServiceException");
        return errorHandler;
    }

    /**
     * 空指针异常 统一处理
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public ErrorHandler exceptionHandler500(NullPointerException e, HttpServletRequest request){
        String message = e.getMessage();
        ErrorHandler errorHandler = ErrorHandler.fail(e.getClass().getName()+ ": " +message);
        log.error("请求的地址：{},出现的空指针异常：{}", request.getRequestURL(), e);
        return errorHandler;
    }

    /**
     * 未知异常 统一处理
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ErrorHandler exceptionHandler(Exception e, HttpServletRequest request){
        String message = e.getMessage();
        if (e instanceof UndeclaredThrowableException){
            Throwable undeclaredThrowable = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            message = undeclaredThrowable.getMessage();
        }
        ErrorHandler errorHandler = ErrorHandler.fail(e.getClass().getName()+ ": " +message);
        log.error("请求的地址：{},出现的异常：{}", request.getRequestURL(), e);
        System.out.println("Exception");
        return errorHandler;
    }
}
